﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.SystemHelp;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    public partial class Settlement : BaseForm
    {
        public Settlement()
        {
            InitializeComponent();
        }

        CarSvc.SoapHeaderClass sopaHeaderCAR = new Aliyeye.Car.Net.UI.CarSvc.SoapHeaderClass();
        ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();

        CarSvc.Car modelCar = new Aliyeye.Car.Net.UI.CarSvc.Car();
        ReserveSvc.Reserve modelReserve = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
        Model.Customer customerInfo = new Model.Customer();

        private int carId = 0;
        private int reserveID = 0;
        private bool isSave = false;
        private bool isCheckout = false;
        private string payType = "";

        public Settlement(int intCarId, int intResID)
        {
            InitializeComponent();

            this.carId = intCarId;
            this.reserveID = intResID;
        }

        public Settlement(int intCarId, int intResID, bool checkout)
        {
            InitializeComponent();

            this.carId = intCarId;
            this.reserveID = intResID;
            this.isCheckout = checkout;
        }

        private void Settlement_Load(object sender, EventArgs e)
        {
            if (!isCheckout)
            {
                lblNowDate1.Text = lblNowDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //endTime = DateTime.Now;
            }

            BindInfo();
        }

        private void BindInfo()
        {

            if (carId > 0)
            {
                overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;

                ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                   proxy => proxy.GetModel(sopaHeaderCAR, carId),
                   result =>
                   {
                       if (result.Error == null)
                       {
                           modelCar = (CarSvc.Car)result.Result;
                           if (modelCar != null)
                           {
                               //车辆信息
                               carCode = lblCarCode.Text = modelCar.Code.ToString();
                               lblDayKm.Text = modelCar.DayLimitKM.ToString();
                               lblOvertimePrie.Text = modelCar.OvertimePrie.ToString();
                               lblTimeoutPrie.Text = modelCar.TimeoutPrie.ToString();
                               //lblCarRent.Text=
                               //lblCarMax.Text = modelCar.Max.ToString();
                               lblCarBrand.Text = modelCar.Brand;
                               lblCartype.Text = modelCar.Cartype;

                               //lblOvertimeAmount.Text = (0 - Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                               //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                               lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                               lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();


                               ReserveSvc.ReserveServiceSoapClient client = new Aliyeye.Car.Net.UI.ReserveSvc.ReserveServiceSoapClient();
                               modelReserve = client.GetModel(sopaHeaderReserveSvc, reserveID);
                               if (modelReserve != null)
                               {
                                   //订单起始公里数
                                   lblCarMax.Text = modelReserve.CurrentMax.ToString();
                                   //客户信息
                                   lblCode.Text = modelReserve.Code;
                                   lblCustomerCode.Text = customerInfo.Code = modelReserve.CustomerCode;
                                   lblCustomerName.Text = customerInfo.Name = modelReserve.CustomerName;
                                   lblCustomerComp.Text = customerInfo.ComName = modelReserve.ComName;
                                   lblCustomerType.Text = modelReserve.CustomerType.Trim() == "1" ? "个人用户" : "企业用户";

                                   lblCarRent.Text = modelReserve.ZPrice + "/" + modelReserve.DeadLineType;

                                   lblBookingDate.Text = modelReserve.BookTime.ToString("yyyy-MM-dd HH:mm:ss");
                                   lblEndBookDate1.Text = lblEndBookDate.Text = modelReserve.EndBooktime.ToString("yyyy-MM-dd HH:mm:ss");
                                   beginTime = modelReserve.BookTime;
                                   endTime = modelReserve.EndBooktime;

                                   //违章保留
                                   lblViolationAmount.Text = modelReserve.IllegalRetention.ToString();

                                   switch (modelReserve.DeadLineType.Trim())
                                   {
                                       case "年":
                                           lblDayKm.Text = modelCar.YearLimitKM.ToString();
                                           lblDayKmTitle.Text = "每年限驶：";
                                           break;
                                       case "月":
                                           lblDayKm.Text = modelCar.MonthLimitKM.ToString();
                                           lblDayKmTitle.Text = "每月限驶：";
                                           break;
                                       case "日":
                                           lblDayKm.Text = modelCar.DayLimitKM.ToString();
                                           lblDayKmTitle.Text = "每日限驶：";
                                           break;
                                   }

                                   string reserveType = "";
                                   // 1: 长租自驾2:短租自驾 3: 长租带驾4:短租带驾
                                   switch (modelReserve.Type)
                                   {
                                       case 1:
                                           reserveType = "长租自驾";
                                           break;
                                       case 2:
                                           reserveType = "短租自驾";
                                           break;
                                       case 3:
                                           reserveType = "长租带驾";
                                           break;
                                       case 4:
                                           reserveType = "短租带驾";
                                           break;
                                   }
                                   lblReserveType.Text = reserveType;

                                   //lblDeposit1.Text = lblDeposit.Text = "-" + modelReserve.Deposit.ToString();
                                   lblDeposit1.Text = lblDeposit.Text = modelReserve.Deposit.ToString();

                                   txtMarks.Text = modelReserve.Marks;
                                   customerInfo.Tel = modelReserve.Tel;
                                   customerInfo.Addr = modelReserve.CustomerAddr;
                                   customerInfo.CodeCar = modelReserve.CustomerCodeCar;
                                   customerInfo.DriCard = modelReserve.CustomerDriCard;
                                   customerInfo.Phone = modelReserve.CustomerPhone;

                                   payType = modelReserve.PayType.Trim();

                                   if (!isCheckout)
                                   {
                                       //超时计算
                                       Int64 timeout = Convert.ToInt64(DateTime.Now.Subtract(modelReserve.EndBooktime).TotalHours);
                                       if (timeout > 0)
                                           lblTimeOut.Text = timeout.ToString();
                                       else
                                           lblTimeOut.Text = "0";

                                       //结算信息
                                       //lblRentReceivable.Text = (0 - modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                                       //lblReceivedAmount.Text = "+" + (modelReserve.Rent + modelReserve.Deposit).ToString();
                                       //lblOvertimeAmount.Text = (0 - Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                                       //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                                       lblRentReceivable.Text = (modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                                       lblReceivedAmount.Text = (modelReserve.Rent + modelReserve.Deposit).ToString();
                                       lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                                       lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                                       GetRepairAndIllegalSumPrice();
                                   }
                                   else
                                   {
                                       this.txtCurrentKM.TextChanged -= new System.EventHandler(this.txtCurrentKM_TextChanged);

                                       lblNowDate.Text = lblNowDate1.Text = modelReserve.SettlementDate.ToString("yyyy-MM-dd HH:mm:ss");

                                       lblRentReceivable.Text = modelReserve.RentReceivable.ToString();
                                       lblReceivedAmount.Text = modelReserve.ReceivedAmount.ToString();
                                       lblOvertimeAmount.Text = modelReserve.OvertimeAmount.ToString();
                                       lblTimeOut.Text = (modelReserve.OvertimeAmount / Convert.ToDecimal(lblTimeoutPrie.Text)).ToString();
                                       lblSuperDriverAmount.Text = modelReserve.SuperDriverAmount.ToString();
                                       lblSuperDriver.Text = (modelReserve.SuperDriverAmount / Convert.ToDecimal(lblOvertimePrie.Text)).ToString();

                                       txtCurrentKM.Text = "***";
                                       txtCurrentKM.Enabled = false;

                                       lblTotalFines1.Text = lblTotalFines.Text = modelReserve.TotalFines.ToString();
                                       lblRepairDamage1.Text = lblRepairDamage.Text = modelReserve.RepairDamage.ToString();
                                       lblTotalAmount.Text = modelReserve.TotalAmount.ToString();
                                       rdbIsCompletedCheckout.Checked = true;
                                       rdbIsCompletedCheckout.Enabled = false;
                                       rdbIsNotCompletedCheckout.Enabled = false;
                                       lblViolationAmount.Text = modelReserve.IllegalRetention.ToString();

                                       //算提前还车金额
                                       this.txtCurrentKM.TextChanged -= new System.EventHandler(this.txtEarlyRefund_TextChanged);
                                       //txtEarlyRefund.Text = (modelReserve.TotalAmount -
                                       //    (modelReserve.ReceivedAmount -
                                       //    modelReserve.RentReceivable -
                                       //    modelReserve.OvertimeAmount -
                                       //    modelReserve.SuperDriverAmount -
                                       //    modelReserve.TotalFines -
                                       //    modelReserve.IllegalRetention -
                                       //    modelReserve.RepairDamage
                                       //    )).ToString();
                                       txtEarlyRefund.Text = modelReserve.EarlyRefund.ToString();
                                       txtEarlyRefund.Enabled = false;
                                   }
                                   overlay.FadeOut(); Cursor.Current = Cursors.Default;

                               }
                           }
                       }
                       else
                       {
                           PageCommon.Error(result.Error.Message);
                           overlay.FadeOut(); Cursor.Current = Cursors.Default;
                       }
                   },
                   this
               );

                #region old

                //if (reserveID > 0)
                //{
                //    ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                //        proxy => proxy.GetModel(sopaHeaderReserveSvc, reserveID),
                //        result =>
                //        {
                //            if (result.Error == null)
                //            {
                //                modelReserve = (ReserveSvc.Reserve)result.Result;

                //                //客户信息
                //                lblCode.Text = modelReserve.Code;
                //                lblCustomerCode.Text = customerInfo.Code = modelReserve.CustomerCode;
                //                lblCustomerName.Text = customerInfo.Name = modelReserve.CustomerName;
                //                lblCustomerComp.Text = customerInfo.ComName = modelReserve.ComName;
                //                lblCustomerType.Text = modelReserve.CustomerType.Trim() == "1" ? "个人用户" : "企业用户";

                //                lblCarRent.Text = modelReserve.ZPrice + "/" + modelReserve.DeadLineType;

                //                lblBookingDate.Text = modelReserve.BookTime.ToString("yyyy-MM-dd HH:mm:ss");
                //                lblEndBookDate1.Text = lblEndBookDate.Text = modelReserve.EndBooktime.ToString("yyyy-MM-dd HH:mm:ss");
                //                beginTime = modelReserve.BookTime;

                //                //违章保留
                //                lblViolationAmount.Text = modelReserve.IllegalRetention.ToString();

                //                switch (modelReserve.DeadLineType.Trim())
                //                {
                //                    case "年":
                //                        lblDayKm.Text = modelCar.YearLimitKM.ToString();
                //                        lblDayKmTitle.Text = "每年限驶：";
                //                        break;
                //                    case "月":
                //                        lblDayKm.Text = modelCar.MonthLimitKM.ToString();
                //                        lblDayKmTitle.Text = "每月限驶：";
                //                        break;
                //                    case "日":
                //                        lblDayKm.Text = modelCar.DayLimitKM.ToString();
                //                        lblDayKmTitle.Text = "每日限驶：";
                //                        break;
                //                }

                //                string reserveType = "";
                //                // 1: 长租自驾2:短租自驾 3: 长租带驾4:短租带驾
                //                switch (modelReserve.Type)
                //                {
                //                    case 1:
                //                        reserveType = "长租自驾";
                //                        break;
                //                    case 2:
                //                        reserveType = "短租自驾";
                //                        break;
                //                    case 3:
                //                        reserveType = "长租带驾";
                //                        break;
                //                    case 4:
                //                        reserveType = "短租带驾";
                //                        break;
                //                }
                //                lblReserveType.Text = reserveType;

                //                //lblDeposit1.Text = lblDeposit.Text = "-" + modelReserve.Deposit.ToString();
                //                lblDeposit1.Text = lblDeposit.Text = modelReserve.Deposit.ToString();

                //                txtMarks.Text = modelReserve.Marks;
                //                customerInfo.Tel = modelReserve.Tel;
                //                customerInfo.Addr = modelReserve.CustomerAddr;
                //                customerInfo.CodeCar = modelReserve.CustomerCodeCar;
                //                customerInfo.DriCard = modelReserve.CustomerDriCard;
                //                customerInfo.Phone = modelReserve.CustomerPhone;

                //                if (!isCheckout)
                //                {
                //                    //超时计算
                //                    Int64 timeout = Convert.ToInt64(DateTime.Now.Subtract(modelReserve.EndBooktime).TotalHours);
                //                    if (timeout > 0)
                //                        lblTimeOut.Text = timeout.ToString();
                //                    else
                //                        lblTimeOut.Text = "0";

                //                    //结算信息
                //                    //lblRentReceivable.Text = (0 - modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                //                    //lblReceivedAmount.Text = "+" + (modelReserve.Rent + modelReserve.Deposit).ToString();
                //                    //lblOvertimeAmount.Text = (0 - Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                //                    //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                //                    lblRentReceivable.Text = (modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                //                    lblReceivedAmount.Text = (modelReserve.Rent + modelReserve.Deposit).ToString();
                //                    lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                //                    lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                //                    GetRepairAndIllegalSumPrice();
                //                }
                //                else
                //                {
                //                    this.txtCurrentKM.TextChanged -= new System.EventHandler(this.txtCurrentKM_TextChanged);

                //                    lblNowDate.Text = lblNowDate1.Text = modelReserve.SettlementDate.ToString("yyyy-MM-dd HH:mm:ss");

                //                    lblRentReceivable.Text = modelReserve.RentReceivable.ToString();
                //                    lblReceivedAmount.Text = modelReserve.ReceivedAmount.ToString();
                //                    lblOvertimeAmount.Text = modelReserve.OvertimeAmount.ToString();
                //                    lblTimeOut.Text = (modelReserve.OvertimeAmount / Convert.ToDecimal(lblTimeoutPrie.Text)).ToString();
                //                    lblSuperDriverAmount.Text = modelReserve.SuperDriverAmount.ToString();
                //                    lblSuperDriver.Text = (modelReserve.SuperDriverAmount / Convert.ToDecimal(lblOvertimePrie.Text)).ToString();

                //                    txtCurrentKM.Text = "***";
                //                    txtCurrentKM.Enabled = false;

                //                    lblTotalFines1.Text = lblTotalFines.Text = modelReserve.TotalFines.ToString();
                //                    lblRepairDamage1.Text = lblRepairDamage.Text = modelReserve.RepairDamage.ToString();
                //                    lblTotalAmount.Text = modelReserve.TotalAmount.ToString();
                //                    rdbIsCompletedCheckout.Checked = true;
                //                    rdbIsCompletedCheckout.Enabled = false;
                //                    rdbIsNotCompletedCheckout.Enabled = false;
                //                    lblViolationAmount.Text = modelReserve.IllegalRetention.ToString();

                //                    //算提前还车金额
                //                    this.txtCurrentKM.TextChanged -= new System.EventHandler(this.txtEarlyRefund_TextChanged);
                //                    txtEarlyRefund.Text = (modelReserve.TotalAmount -
                //                        (modelReserve.ReceivedAmount -
                //                        modelReserve.RentReceivable -
                //                        modelReserve.OvertimeAmount -
                //                        modelReserve.SuperDriverAmount -
                //                        modelReserve.TotalFines -
                //                        modelReserve.IllegalRetention -
                //                        modelReserve.RepairDamage
                //                        )).ToString();
                //                    txtEarlyRefund.Enabled = false;
                //                }
                //                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                //            }
                //            else
                //            {
                //                PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                //            }
                //        },
                //        this
                //    );
                //}
                #endregion
            }
        }
        string carCode = string.Empty;
        DateTime beginTime = new DateTime(1900, 1, 1);
        DateTime endTime = new DateTime(1900, 1, 1);
        string illeglKeys = "";

        private void GetRepairAndIllegalSumPrice()
        {
            RepairSvc.SoapHeaderClass sopaHeaderRepair = new Aliyeye.Car.Net.UI.RepairSvc.SoapHeaderClass();
            IllegalSvc.SoapHeaderClass sopaHeaderIllegal = new Aliyeye.Car.Net.UI.IllegalSvc.SoapHeaderClass();
            //overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;

            RepairSvc.RepairServiceSoapClient repairClient = new Aliyeye.Car.Net.UI.RepairSvc.RepairServiceSoapClient();
            lblRepairDamage1.Text = lblRepairDamage.Text = repairClient.GetSumPriceByCarCode(sopaHeaderRepair, carCode, beginTime, endTime).ToString();

            IllegalSvc.IllegalServiceSoapClient IllegalClient = new Aliyeye.Car.Net.UI.IllegalSvc.IllegalServiceSoapClient();
            lblTotalFines1.Text = lblTotalFines.Text = IllegalClient.GetSumPriceByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime).ToString();

            DataSet dsIllegalKeys = IllegalClient.GetKeysByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime);
            if (dsIllegalKeys != null && dsIllegalKeys.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in dsIllegalKeys.Tables[0].Rows)
                    illeglKeys += dr["Id"].ToString().Trim() + ",";
                illeglKeys = illeglKeys.Substring(0, illeglKeys.Length - 1);
                lklblIllegalCount.Text = dsIllegalKeys.Tables[0].Rows.Count + " 笔";
            }
            GetTotalAmount();
        }

        private bool IsNumberMoney(System.Windows.Forms.TextBox t, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' || e.KeyChar == 8 || e.KeyChar == 13))
            {
                return true;
            }
            else
            {
                PageCommon.Alert("只能输入数字！");
                e.Handled = true;
                return false;
            }
        }

        private void txtCurrentKM_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtCurrentKM, e);
        }

        private void txtCurrentKM_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCurrentKM.Text))
            {
                PageCommon.Alert("当前公里数不能为空！");
                return;
            }
            Int64 LimitKM = 0;
            switch (modelReserve.DeadLineType.Trim())
            {
                case "年":
                    LimitKM = modelCar.YearLimitKM;
                    break;
                case "月":
                    LimitKM = modelCar.MonthLimitKM;
                    break;
                case "日":
                    LimitKM = modelCar.DayLimitKM;
                    break;
                case "次":
                    LimitKM = modelCar.DayLimitKM;
                    break;
            }

            Int64 sumLimitKM = LimitKM * modelReserve.DeadLine;

            Int64 km = Convert.ToInt64(txtCurrentKM.Text) - sumLimitKM - Convert.ToInt64(lblCarMax.Text);
            if (km > 0)
                lblSuperDriver.Text = km.ToString();
            else
                lblSuperDriver.Text = "0";

            //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();
            lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

            GetTotalAmount();
        }

        private void GetTotalAmount()
        {
            decimal sum = Convert.ToDecimal(lblReceivedAmount.Text) -
                Convert.ToDecimal(lblRentReceivable.Text) -
                Convert.ToDecimal(lblOvertimeAmount.Text) -
                Convert.ToDecimal(lblSuperDriverAmount.Text) -
                Convert.ToDecimal(lblTotalFines.Text) -
                //Convert.ToDecimal(lblDeposit.Text) +
                Convert.ToDecimal(lblViolationAmount.Text) -
                Convert.ToDecimal(lblRepairDamage.Text) +
                Convert.ToDecimal(txtEarlyRefund.Text);

            lblTotalAmount.Text = sum.ToString();

            if (sum > 0)
                lblTotalAmount.ForeColor = Color.Blue;
            else
                lblTotalAmount.ForeColor = Color.Red;

            lblReceivedAmountNow.Text = "-->   " + (Convert.ToDecimal(lblReceivedAmount.Text) - Convert.ToDecimal(lblTotalAmount.Text)).ToString();

        }

        //结算
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveInfo();
        }

        private void SaveInfo()
        {
            if (!isCheckout)
            {
                if (string.IsNullOrEmpty(txtCurrentKM.Text))
                {
                    PageCommon.Alert("请输入当前公里数！");
                    return;
                }

                if (Convert.ToDecimal(txtCurrentKM.Text) < Convert.ToDecimal(lblCarMax.Text))
                {
                    PageCommon.Alert("当前公里必须大于出车里数，请重新输入当前公里数！");
                    return;
                }
            }

            ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
            //ReserveSvc.Reserve model = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
            decimal InputBillingAmount = -Convert.ToDecimal(lblTotalAmount.Text);
            Int64 currentMax = 0;
            long points = 0;

            if (!isCheckout)
            {
                //餐费住宿费
                decimal MealsAccommodation = 0;
                //违章保留
                decimal IllegalRetention = Convert.ToDecimal(lblViolationAmount.Text);
                modelReserve.MealsAccommodation = MealsAccommodation;
                modelReserve.IllegalRetention = IllegalRetention;
                modelReserve.Marks = txtMarks.Text;
                modelReserve.RentReceivable = Convert.ToDecimal(lblRentReceivable.Text);
                modelReserve.OvertimeAmount = Convert.ToDecimal(lblOvertimeAmount.Text);
                modelReserve.SuperDriverAmount = Convert.ToDecimal(lblSuperDriverAmount.Text);
                modelReserve.TotalFines = Convert.ToDecimal(lblTotalFines.Text);
                modelReserve.DepositReturn = Convert.ToDecimal(lblDeposit.Text);
                modelReserve.RepairDamage = Convert.ToDecimal(lblRepairDamage.Text);

                currentMax = Convert.ToInt64(txtCurrentKM.Text);
                if (rdbIsNotCompletedCheckout.Checked)
                {
                    modelReserve.ReceivedAmount = Convert.ToDecimal(lblReceivedAmount.Text);
                    modelReserve.TotalAmount = Convert.ToDecimal(lblTotalAmount.Text);
                    modelReserve.IsCompletedCheckout = false;
                }
                else
                {
                    modelReserve.ReceivedAmount = Convert.ToDecimal(lblReceivedAmount.Text) - Convert.ToDecimal(lblTotalAmount.Text);
                    modelReserve.TotalAmount = 0;
                    modelReserve.IsCompletedCheckout = true;

                    //获取会员积分
                    if (payType.Trim() != "会员积分")
                    {
                        ArchivesSvc.SoapHeaderClass sopaHeader = new ArchivesSvc.SoapHeaderClass();
                        ArchivesSvc.ArchivesServiceSoapClient client = new Aliyeye.Car.Net.UI.ArchivesSvc.ArchivesServiceSoapClient();
                        float rate = client.GetPointsRate(sopaHeader);

                        decimal sum = (modelReserve.RentReceivable + modelReserve.OvertimeAmount + modelReserve.SuperDriverAmount) * Convert.ToDecimal(rate);

                        points = Convert.ToInt64(Math.Round(sum, 0));
                        modelReserve.Points = points;
                        modelReserve.PointRate = rate;
                    }
                }
                modelReserve.IsReturnIllegal = false;
            }
            else
            {
                modelReserve.ReceivedAmount = Convert.ToDecimal(lblReceivedAmount.Text) - Convert.ToDecimal(lblTotalAmount.Text);
                modelReserve.TotalAmount = 0;
                modelReserve.IsCompletedCheckout = true;
                modelReserve.IsReturnIllegal = false;
            }
            modelReserve.SettlementDate = Convert.ToDateTime(lblNowDate.Text);
            modelReserve.SettlementUserID = Login.LogUserId;
            modelReserve.EarlyRefund = Convert.ToDecimal(txtEarlyRefund.Text);

            ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
            proxy => proxy.FinishOrder(sopaHeaderReserveSvc, modelCar.Id, modelReserve.Id, currentMax, modelReserve, InputBillingAmount),
            result =>
            {
                if (result.Error == null)
                {
                    //更改违章付款状态
                    IllegalSvc.SoapHeaderClass sopaHeaderIllegal = new Aliyeye.Car.Net.UI.IllegalSvc.SoapHeaderClass();
                    IllegalSvc.IllegalServiceSoapClient IllegalClient = new Aliyeye.Car.Net.UI.IllegalSvc.IllegalServiceSoapClient();
                    if (illeglKeys != "")
                        IllegalClient.GetUpdateStatusByKeysByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime, illeglKeys);
                    PageCommon.Notify("还车结算成功！");
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    txtCurrentKM.Enabled = false;
                    txtMarks.Enabled = false;
                    btnSave.Enabled = false;
                    rdbIsCompletedCheckout.Enabled = false;
                    rdbIsNotCompletedCheckout.Enabled = false;

                    txtEarlyRefund.Enabled = false;

                    isSave = true;
                    btnSave.Enabled = false;
                }
                else
                {
                    PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
            },
            this
            );
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                if (PageCommon.Confirm("你还未结算，现在结算吗？"))
                {
                    SaveInfo();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        private void picbBills_Click(object sender, EventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

        private void lklblShowDetails_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

        //打印单据
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                PageCommon.Alert("请先结算，再打印单据！");
                return;
            }

            DataSet ds = null;
            CompanySvc.SoapHeaderClass sopaHeaderCompany = new CompanySvc.SoapHeaderClass();
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ServiceManipulator.SafeAsyncExecution<CompanySvc.CompanyServiceSoapClient>(
                    proxy => proxy.GetList(sopaHeaderCompany, ""),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            ds = (DataSet)result.Result;
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                Model.Company model = new Model.Company();

                                model.ComName = ds.Tables[0].Rows[0]["ComName"].ToString();
                                model.ComAddr = ds.Tables[0].Rows[0]["ComAddr"].ToString();
                                model.Tel = ds.Tables[0].Rows[0]["Tel"].ToString();
                                model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                                model.Url = ds.Tables[0].Rows[0]["Url"].ToString();
                                model.Marks = ds.Tables[0].Rows[0]["Marks"].ToString();

                                decimal earlyRefund = Convert.ToDecimal(txtEarlyRefund.Text);

                                //开始打印结算单
                                WordHelper wordHelp = new WordHelper();
                                if (wordHelp.PrintSettlement(model, customerInfo, modelReserve, modelCar, rdbIsCompletedCheckout.Checked, Convert.ToDecimal(lblTotalAmount.Text), Login.LogTrueName, earlyRefund))
                                {
                                    PageCommon.Notify("打印成功！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                                else
                                {
                                    PageCommon.Alert("打印失败！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                            }
                            else
                            {
                                PageCommon.Alert("打印失败！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
        }

        private void txtEarlyRefund_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtEarlyRefund.Text))
            {
                PageCommon.Alert("提前退车不能为空！");
                txtEarlyRefund.Text = "0";
                return;
            }
            GetTotalAmount();
        }

        private void lblNowDate_Click(object sender, EventArgs e)
        {
            this.dtpReturnDate.Visible = true;
            dtpReturnDate.Value = Convert.ToDateTime(lblNowDate.Text);
        }

        private void dtpReturnDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                lblNowDate.Text = dtpReturnDate.Value.ToString("yyyy-MM-dd HH:mm:00");
                dtpReturnDate.Visible = false;

                DateTime dtReturn = Convert.ToDateTime(lblNowDate.Text);
                //超时计算
                Int64 timeout = Convert.ToInt64(dtReturn.Subtract(modelReserve.EndBooktime).TotalHours);
                if (timeout > 0)
                    lblTimeOut.Text = timeout.ToString();
                else
                    lblTimeOut.Text = "0";

                lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();

                GetTotalAmount();
            }
        }

        private void lklblIllegalCount_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lklblIllegalCount.Text == "0 笔")
            {
                PageCommon.Notify("暂无违章罚单！");
                return;
            }
            IllegalList userForm = new IllegalList(reserveID);
            userForm.ShowDialog();
        }

        private void rdbIsCompletedCheckout_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbIsCompletedCheckout.Checked)
            {
                lblReceivedAmountNow.Text = "-->   " + (Convert.ToDecimal(lblReceivedAmount.Text) - Convert.ToDecimal(lblTotalAmount.Text)).ToString();
                lblReceivedAmountNow.Visible = true;
            }
            else
            {
                lblReceivedAmountNow.Text = "";
                lblReceivedAmountNow.Visible = false;
            }
        }
    }
}
